package com.zyg.seckill.controller;

import com.alipay.api.AlipayApiException;
import com.zyg.common.entity.PayAsyncVo;
import com.zyg.common.entity.PayVo;

import com.zyg.common.entity.TbPayLog;
import com.zyg.common.utils.AlipayTemplate;
import com.zyg.seckill.entity.TbSeckillOrder;
import com.zyg.seckill.service.PayService;
import com.zyg.seckill.service.SeckillOrderService;
import org.jasig.cas.client.authentication.AttributePrincipal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


@Controller
public class SeckillOrderController {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private SeckillOrderService orderService;
    @Autowired
    private AlipayTemplate alipayTemplate;
    @Autowired
    private PayService payService;
    //功能: 1. 秒杀下单，下单成功后跳转到支付页面

    @GetMapping("/seckill/saveOrder/{id}")
    public String saveOrder(@PathVariable Integer id, Model model){
        //得到当前登录的用户名
        String username = getLoginName();

        //为了保证秒杀商品的公平性，我们需要在redis中存放用户信息
        TbSeckillOrder seckillOrder = orderService.saveOrder(username, id);

        //将订单号保存到model中
        model.addAttribute("outTradeNo",seckillOrder.getId());
        return "pay";
    }

    //功能: 2. 获取登录名

    private String getLoginName() {
        //4.1 获取用户名（cas登录名的获取方式）
        AttributePrincipal principal = (AttributePrincipal) request.getUserPrincipal();
        return principal.getName();
    }

    //功能: 3. 秒杀支付

    @GetMapping("/seckill/pay/{type}/{outTradeNo}")
    @ResponseBody
    public String seckillPay(@PathVariable int type,@PathVariable String outTradeNo) throws AlipayApiException {
        //3.0 得到当前登录名
        String username = getLoginName();
        //3.1 从redis中得到支付日志
        TbPayLog payLog = orderService.getPayLoyFromRedis(username);
        //3.2 构造PayVo对象
        PayVo vo = new PayVo(outTradeNo,payLog.getTotalFee() + "","泽易购","泽易购秒杀");
        //3.3 返回调用结果
        String result = alipayTemplate.pay(vo, type);
        //3.3 返回
        return result;

    }

    //功能: 4. 根据当前登录用户，查询此用户的所有订单列表

    @GetMapping("seckill/order/getOrderList")
    public String getOrderList(Model model){
        // 4.1 获取登录名
        String loginName = getLoginName();
        // 4.2 获取此登录名对应的订单列表
        TbSeckillOrder orderList = orderService.getOrderList(loginName);
        // 4.3 将订单列表放到model中
        model.addAttribute("seckillOrder",orderList);

        return "orderlist";
    }

    //功能: 【支付宝异步回调】

    @PostMapping("/seckill/pay")
    @ResponseBody
    public String syncCallback(PayAsyncVo vo, HttpServletRequest request){
        System.out.println("vo = " + vo);
        //得支支付宝后台传入的数据
        Map<String,String> params = new HashMap<>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        //得到登录名
        //String loginName = getLoginName();

        //进行验签处理
        String result = payService.validSignature(vo,params);
        System.out.println("result = " + result);
        //返回
        return result;
    }
}